using System;
using System.Collections.Generic;
using SubForum.DataAccess;
using SubForum.DataAccess.Objects;
using SubForum.ObjectModel.Posts;
using SubForum.ObjectModel.PostStatuses;
using SubForum.Web.Services;
using SubForum.ObjectModel.Tags;
using System.Transactions;
using System.Web.Mvc;
using SubForum.Framework.Utilities;


namespace SubForum.Web.Controllers
{
    public class ForumController : Controller
    {

        public ForumController()
        {

        }

        private DataService DataAccessService
        {
            get { return DataAccessManager.GetDataAccessService(); }
        }

        //
        // GET: /Website/
        public ActionResult UserPosts()
        {

            string user = RouteData.Values["user"] as string;
            string slug = RouteData.Values["slug"] as string;
            PostList<DiscussionPost> pl = new PostList<DiscussionPost>();

            IList<DiscussionPost> posts = null;

            if (string.IsNullOrEmpty(user))
                return View();

            bool postidSuccess = false;

            //Try with slug
            if (!postidSuccess)
            {               
                posts = DataAccessService.GetPostBySlug(slug);
            }

            pl.AddRange(posts);

            return View(pl);

        }

        public ActionResult Index()
        {

            PostList<DiscussionPost> pl = new PostList<DiscussionPost>();
            var a = DataAccessService.GetTopTenDiscussions();

            pl.AddRange(a);

            return View(pl);

        }

        public ActionResult Tag()
        {
            string tagName = RouteData.Values["id"] as string;
            if (string.IsNullOrEmpty(tagName))
                return View();

            IList<DiscussionPost> posts = DataAccessService.GetPostsByTag(tagName);
            PostList<DiscussionPost> pl = new PostList<DiscussionPost>();
            pl.AddRange(posts);

            return View("Index", pl);
        }

        public ActionResult Post()
        {
            try
            {
                string id = RouteData.Values["id"] as string;
                string user = RouteData.Values["user"] as string;
                string slug = RouteData.Values["slug"] as string;
        
                IList<DiscussionPost> posts = null;

                if (string.IsNullOrEmpty(id))
                    return View();
                
                bool postidSuccess = false;

                //try with encoded guid
                try
                {
                    Guid postid = ShortGuid.Decode(id);
                    posts = DataAccessService.GetPostById(postid);
                    if( posts.Count>0)
                        postidSuccess = true;
                }
                catch { }

                //Try with slug
                if (!postidSuccess)
                {
                     slug = id;
                    posts = DataAccessService.GetPostBySlug(slug);
                }

                if (posts != null && posts.Count > 0)
                {
                    posts[0].Tags.AddRange(DataAccessService.GetPostTags(posts[0].PostId));
                    posts[0].Threads.AddRange(DataAccessService.GetPostChildren(posts[0].PostId));
                    return View(posts[0]);
                }
                else
                {
                    base.RedirectToAction("Error");
                }
            }
            catch
            {
                return View("Error");
            }

            return View();
        }

        public ActionResult Error()
        {
            return View("Error");
        }

        public ActionResult TagCloud()
        {

            IList<TagCount> tagCountList = DataAccessService.GetTagCloud();
 
            return View(tagCountList);
        }

        public ActionResult DeletePost(DiscussionPost post)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                //DataAccessService.(new List<DiscussionPost>() { post });
                //DataAccessService.InsertPostTags(post.Tags);
                //ts.Complete();
            }

            return RedirectToAction("Index", "Forum");
        }


        public static string GetTagClass(int category, int articles)
        {
            var result = (category * 100) / articles;
            if (result <= 1)
                return "tag1";
            if (result <= 4)
                return "tag2";
            if (result <= 8)
                return "tag3";
            if (result <= 12)
                return "tag4";
            if (result <= 18)
                return "tag5";
            if (result <= 30)
                return "tag5";

            return result <= 50 ? "tag6" : "";
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult PostMessage(string BodyText, string TitleText,
            string TagsText, string RootPostId)
        {
            BodyText = HtmlUtils.Sanitize(BodyText);

            DiscussionPost post = new DiscussionPost()
            {
                BodyText = BodyText,
                TitleText = TitleText,
                TagsText = TagsText
            };

            if (ValidatePost(TitleText, BodyText, TagsText))
            {

                if (!RootPostId.Equals(ShortGuid.Encode(new Guid().ToString())))
                {
                    post.RootPost = new DiscussionPost();
                    post.RootPost.SetIdFromShortId(RootPostId);
                }


                post.PostDate = DateTime.Now;
                post.PostId = Guid.NewGuid();
                post.Slug = Slug.GenerateSlug(post.TitleText);
                post.PostType = PostType.Discussion;
                post.PostStatus = PostStatusType.Open;
                post.PostedBy = new SubForum.ObjectModel.Users.UserProfile() { UserName = User.Identity.Name };
                post.Tags = new TagList<SubForum.ObjectModel.Tags.Tag>(post.TagsText, post);

                //using (TransactionScope ts = new TransactionScope())
                //{
                DataAccessService.InsertDiscussionPost(new List<DiscussionPost>() { post });

                if (post.RootPost != null)
                {
                    DataAccessService.InsertPostRelation(new List<DiscussionPost>() { post });
                }

                DataAccessService.InsertPostTags(post.Tags);
                //    ts.Complete();
                //}

                if (post.RootPost != null)
                {
                    return RedirectToAction("/Post/" + post.RootPost.GetShortId(), "Forum");
                }
                else
                {
                    return RedirectToAction("Index", "Forum");
                }
            }
            
            return PartialView(post);
        }


        private bool ValidatePost(string title, string body, string tags)
        {
            if (String.IsNullOrEmpty(title))
            {
                ModelState.AddModelError("TitleText", "The post's title cannot be left blank.");
            }
            if (String.IsNullOrEmpty(body))
            {
                ModelState.AddModelError("BodyText", "The post must have a message body.");
            }

            if (String.IsNullOrEmpty(body))
            {
                ModelState.AddModelError("TagsText", "The post must have tags associated with it.");
            }
            
            return ModelState.IsValid;
        }
    }
}
